# -*- coding:utf-8 -*-
# time: 2025/8/9 ♡  13:59
# author:张伟
from functools import wraps
from flask import g, request
from flask_jwt_extended import verify_jwt_in_request, decode_token, get_jwt_identity

from utils import restful


def check_Permission(permission):
    def outter(func):
        @wraps(func)
        def inner(*args, **kwargs):
            user = getattr(g, "user")
            if not user:
                return restful.unlogin_error()
            if user.has_permission(permission):
                return func(*args, **kwargs)
            else:
                return restful.permission_error()

        return inner

    return outter


# 双jwt验证器 - 只做验证，不刷新token
def jwt_optional_with_user():
    def wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            # 对于豁免的端点，即使token验证失败也继续执行
            if request.endpoint in ['cmsapi.refresh_token']:
                return func(*args, **kwargs)
            try:
                # 验证Access Token
                verify_jwt_in_request()
                # 检查是否有Refresh Token
                refresh_token = request.headers.get("X-Refresh-Token")
                if refresh_token:
                    try:
                        # 验证Refresh Token的有效性
                        decoded_refresh = decode_token(refresh_token)
                        # 获取access token中的用户身份
                        access_identity = get_jwt_identity()
                        # 获取refresh token中的用户身份
                        refresh_identity = decoded_refresh['identity']
                        # 验证两个token是否属于同一用户
                        if access_identity != refresh_identity:
                            return restful.unlogin_error(message="Token不匹配")
                    except Exception as e:

                        return restful.unlogin_error(message="Refresh Token无效")
                return func(*args, **kwargs)
            except Exception as e:
                # 对于豁免的端点，即使token验证失败也继续执行
                if request.endpoint in ['cmsapi.refresh_token']:
                    return func(*args, **kwargs)
                return restful.unlogin_error(message="Access Token无效")

        return inner

    return wrapper
